package com.topcent.tioxyc.xxljob;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.pojo.InvoiceDocument;
import com.topcent.tioxyc.pojo.PaymentForm;
import com.topcent.tioxyc.pojo.SAPPurchaseOrder;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.topcent.tioxyc.util.PurchaseCommunity;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: weidian
 * @date: 2024/12/24 09:37
 * @Description: 付款单定时任务
 */
@Slf4j
@Component
public class FukuanXxlJob {

    @XxlJob("fukuan")
    public String fukuan() {
        List<PaymentForm> fukuandans = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
        // 付款单页面：669cb70dab60aa3f4a7bb8b2
        parameter.put("entry_id", "669cb70dab60aa3f4a7bb8b2");

        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "flowState");
        cond.put("type", "flowstate");
        cond.put("method", "eq");
        List<Integer> values = new ArrayList<>();
        values.add(1);
        cond.put("value", values);
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<PaymentForm> list = JSONUtil.toList(objects, PaymentForm.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            fukuandans.addAll(list);
        } while (fale);

        List<PaymentForm> weikuan = new ArrayList<>();

        for (PaymentForm fukuandan : fukuandans) {
            if (!fukuandan.get_widget_1721548605263().isEmpty()) {
                weikuan.add(fukuandan);
            }
        }
        Map<String, Object> parameterCxv = new HashMap<>();
        parameterCxv.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
        // 入库凭证：66a3727ee9d0a8542c969091
        parameterCxv.put("entry_id", "66a3727ee9d0a8542c969091");
        for (PaymentForm paymentForm : weikuan) {
            for (PaymentForm.OrderFinalPayment orderFinalPayment : paymentForm.get_widget_1721548605263()) {
                if (orderFinalPayment.get_widget_1727334556949() == null || orderFinalPayment.get_widget_1727334556949().isEmpty() ||
                        orderFinalPayment.get_widget_1721548605264() == null || orderFinalPayment.get_widget_1721548605264().isEmpty()
                        || orderFinalPayment.get_widget_1721548605265() == null) {
                    continue; // 跳过当前遍历
                }

                HashMap<String, String> communti = new HashMap<>();
                communti.put("_widget_1727315685608", orderFinalPayment.get_widget_1727334556949());
                communti.put("_widget_1721987711273", orderFinalPayment.get_widget_1721548605264());
                List<InvoiceDocument> invoiceDocuments = PurchaseCommunity.queryBased(parameterCxv, headers, communti, InvoiceDocument.class);
                if (invoiceDocuments == null || invoiceDocuments.isEmpty()) {
                    continue; // 跳过当前遍历
                }
                // 获取尾款占比
                BigDecimal finalPaymentRate = BigDecimal.valueOf(orderFinalPayment.get_widget_1721548605265());

                // 定义变量用于存储分摊金额总和和未付金额总和
                BigDecimal totalAllocationAmount = BigDecimal.ZERO;
                BigDecimal totalUnpaidAmount = BigDecimal.ZERO;
                BigDecimal totalBalanceAmount = BigDecimal.ZERO;
                InvoiceDocument document = invoiceDocuments.getFirst();
                // 把同一个付款单金额合计起来
                List<PaymentForm> weikuand = new ArrayList<>();
                for (PaymentForm form : weikuan) {
                    for (PaymentForm.OrderFinalPayment finalPayment : form.get_widget_1721548605263()) {
                        String widget1727334556949 = finalPayment.get_widget_1727334556949();
                        if (widget1727334556949.equals(orderFinalPayment.get_widget_1727334556949()) &&
                                finalPayment.get_widget_1721548605264().equals(orderFinalPayment.get_widget_1721548605264())) {
                            weikuand.add(form);
                        }
                    }
                }

                Map<String, BigDecimal> jine = new HashMap<>();
                if (weikuand.size() > 1) {
                    for (PaymentForm form : weikuand) {
                        for (PaymentForm.OrderFinalPayment finalPayment : form.get_widget_1721548605263()) {
                            if (finalPayment.get_widget_1727334556949().equals(orderFinalPayment.get_widget_1727334556949()) &&
                                    finalPayment.get_widget_1721548605264().equals(orderFinalPayment.get_widget_1721548605264())) {
                                BigDecimal fkbl = BigDecimal.valueOf(finalPayment.get_widget_1721548605265());
                                for (InvoiceDocument.InvoiceLineItem invoiceLineItem : document.get_widget_1727340673732()) {

                                    BigDecimal allocationAmount = invoiceLineItem.get_widget_1727340673745()
                                            .multiply(fkbl)
                                            .setScale(10, RoundingMode.HALF_UP);
                                    // 获取键值
                                    String key = invoiceLineItem.get_widget_1727340673742();

                                    // 检查并处理累加逻辑
                                    jine.put(key, allocationAmount.add(jine.getOrDefault(key, BigDecimal.ZERO)));

                                }
                            }
                        }
                    }
                }
                for (InvoiceDocument.InvoiceLineItem invoiceLineItem : document.get_widget_1727340673732()) {
                    //把其他采购订单的付款金额拿过来。
                    Map<String, Object> cgdd = new HashMap<>();
                    cgdd.put("app_id", "6690c7633df0f4b90b4ef551");
                    //采购订单_拷贝数据（陈志生）669df675b02f2a74e35ca2f9
                    cgdd.put("entry_id", "669df675b02f2a74e35ca2f9");
                    HashMap<String, String> cgdds = new HashMap<>();
                    cgdds.put("_widget_1721628277543", invoiceLineItem.get_widget_1727340673739());
                    cgdds.put("_widget_1721628277558", invoiceLineItem.get_widget_1727340673735());
                    List<SAPPurchaseOrder> sapPurchaseOrders = PurchaseCommunity.queryBased(cgdd, headers, cgdds, SAPPurchaseOrder.class);
                    if (sapPurchaseOrders.isEmpty() || sapPurchaseOrders.getFirst() == null ||
                            sapPurchaseOrders.getFirst().get_widget_1724225500094() == null) {
                        continue;
                    }


                    // 如果采购订单查询结果不为空，取出已付金额
                    /*BigDecimal paidAmount = sapPurchaseOrders.isEmpty() || sapPurchaseOrders.getFirst() == null ||
                            sapPurchaseOrders.getFirst().get_widget_1722475785243() == null
                            ? BigDecimal.ZERO
                            : BigDecimal.valueOf(sapPurchaseOrders.getFirst().get_widget_1722475785243());*/

                    // 计算已付金额
                    BigDecimal allocationAmount = invoiceLineItem.get_widget_1727340673745()
                            .multiply(finalPaymentRate)
                            .setScale(10, RoundingMode.HALF_UP);


                    if (weikuand.size() == 1) {
                        // _widget_1731575068806 ： 明细表.已付金额
                        invoiceLineItem.set_widget_1731575068806(allocationAmount);
                    } else {
                        jine.forEach((key, value) -> {
                            if (key.equals(invoiceLineItem.get_widget_1727340673742())) {
                                invoiceLineItem.set_widget_1731575068806(allocationAmount.add(value));
                            }
                        });
                    }
                    // 如果原分摊字段有数据，累加现有值；否则直接写入
//                    BigDecimal existingAllocationAmount = invoiceLineItem.get_widget_1731575068806();
//                    if (existingAllocationAmount != null) {
//                        allocationAmount = allocationAmount.add(existingAllocationAmount);
//                    }


                    // 计算未付金额
                    BigDecimal zongshu = invoiceLineItem.get_widget_1727340673745();
                    //隐藏.add(sapPurchaseOrders.getFirst().get_widget_1724225500094());

                    BigDecimal unpaidAmount = zongshu
                            .subtract(allocationAmount)
                            //.subtract(paidAmount)
                            .setScale(10, RoundingMode.HALF_UP);

                    // _widget_1731575068807 明细表.未付金额
                    invoiceLineItem.set_widget_1731575068807(unpaidAmount);


                    // 计算分摊总金额累加值：已付金额减去未付金额，加上当前行的分摊金额
                    BigDecimal allocationAdjustment = allocationAmount;/*paidAmount
                            .add(allocationAmount);*/

                    // 累加到分摊金额总和和未付金额总和
                    totalAllocationAmount = totalAllocationAmount.add(allocationAdjustment);
                    totalUnpaidAmount = totalUnpaidAmount.add(unpaidAmount);
                    totalBalanceAmount = totalBalanceAmount.add(invoiceLineItem.get_widget_1727340673745().subtract(allocationAmount));

                    // 处理尾款的采购订单_拷贝数据表逻辑 669df675b02f2a74e35ca2f9
                    sapPurchaseOrders.getFirst().set_widget_1722475785243(allocationAdjustment.setScale(2, RoundingMode.HALF_UP).doubleValue());
                    sapPurchaseOrders.getFirst().set_widget_1731911494439(unpaidAmount);
                    sapPurchaseOrders.getFirst().set_widget_1722475785245(allocationAmount.setScale(2, RoundingMode.HALF_UP).doubleValue());

                    Map<String, Object> parameterEnd = new HashMap<>();
                    parameterEnd.put("app_id", "6690c7633df0f4b90b4ef551");
                    //采购订单_拷贝数据（陈志生）669df675b02f2a74e35ca2f9
                    parameterEnd.put("entry_id", "669df675b02f2a74e35ca2f9");
                    parameterEnd.put("is_start_trigger", "true");
                    parameterEnd.put("data_id", sapPurchaseOrders.getFirst().get_id());
                    sapPurchaseOrders.getFirst().set_id(null);
                    parameterEnd.put("data", ConnmeUtils.convertEntityToMapNull(sapPurchaseOrders.getFirst()));
                    String jsonSaleEnd = JSONUtil.toJsonStr(parameterEnd);
                    log.info("Modified sales order prepayment: " + jsonSaleEnd);
                    ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSaleEnd);
                }

                // 输出分摊金额总和和未付金额总和到总记录
                BigDecimal existingTotalAllocationAmount = BigDecimal.ZERO;
                BigDecimal existingTotalUnpaidAmount = BigDecimal.ZERO;

                totalAllocationAmount = totalAllocationAmount.add(existingTotalAllocationAmount);
                totalUnpaidAmount = totalUnpaidAmount.add(existingTotalUnpaidAmount);

                // 已付总金额、未付金额、尾款未付总金额
                invoiceDocuments.getFirst().set_widget_1731638214169(totalAllocationAmount);
                invoiceDocuments.getFirst().set_widget_1731638214170(totalUnpaidAmount);
                invoiceDocuments.getFirst().set_widget_1731915520417(totalBalanceAmount);


                Map<String, Object> parameterInster = new HashMap<>();
                parameterInster.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
                // 入库凭证：66a3727ee9d0a8542c969091
                parameterInster.put("entry_id", "66a3727ee9d0a8542c969091");
                parameterInster.put("is_start_trigger", "true");
                parameterInster.put("data_id", invoiceDocuments.getFirst().get_id());
                invoiceDocuments.getFirst().set_id(null);
                parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(invoiceDocuments.getFirst()));
                String jsonSalee = JSONUtil.toJsonStr(parameterInster);
                ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
            }
        }


        return "suu===" + weikuan.size();
    }
}
